package org.jeecg.chase.modules.api.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.ImmutableMap;
import org.jeecg.chase.common.dataaccess.core.BaseNamedParameterJdbcTemplate;
import org.jeecg.chase.modules.adhuser.entity.AdhUser;
import org.jeecg.chase.modules.entity.AdhCouponInfo;
import org.jeecg.chase.modules.merch.entity.AdhMerchInfo;
import org.jeecg.chase.modules.merch.service.IAdhMerchInfoService;
import org.jeecg.chase.modules.order.entity.AdhCouponOrder;
import org.jeecg.chase.modules.order.service.IAdhCouponOrderService;
import org.jeecg.chase.modules.service.IAdhCouponInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author leikai
 * @version 1.0
 * @description: api service
 * @date 2022/03/10/0010 15:55
 */
@Service
@Transactional
public class ApiService {

    @Autowired
    private IAdhCouponInfoService iAdhCouponInfoService;

    @Autowired
    private IAdhMerchInfoService adhMerchInfoService;

    @Autowired
    private IAdhCouponOrderService iAdhCouponOrderService;

    @Autowired
    private BaseNamedParameterJdbcTemplate jdbcTemplate;


    /**
     * 根据分类ID，获取商户列表
     *
     * @param categoryId
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @author leikai
     * @date 2022/03/10/0010 15:58
     */
    public List<Map<String, Object>> queryMerchList(String categoryId) {
        String sql = "SELECT id,merch_name,merch_logo FROM adh_merch_info WHERE merch_category=:categoryId and merch_status='1'";
        return this.jdbcTemplate.queryForListHump(sql, ImmutableMap.of("categoryId", categoryId));
    }

    /**
     * 查询商户详情
     *
     * @param merchId 商户id
     * @param userId  用户id
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author leikai
     * @date 2022/03/10/0010 22:39
     */
    public Map<String, Object> getMerchInfo(String merchId, String userId) {
        String sql = "SELECT a.*,IF(b.merch_id IS NOT NULL,1,0) AS if_focus FROM adh_merch_info a\n" +
                "LEFT JOIN(\n" +
                "\tSELECT merch_id FROM adh_user_merch_focus WHERE user_id=:userId\n" +
                ") b ON a.id=b.merch_id WHERE a.id=:merchId";
        return this.jdbcTemplate.queryForMapHump(sql, ImmutableMap.of("merchId", merchId, "userId", userId));
    }

    /**
     * @param merchId
     * @param couponId
     * @param user
     * @return java.lang.String
     * @author leikai
     * @date 2022/03/11/0011 18:32
     */
    public Map<String, String> receiveCoupon(String merchId, String couponId, AdhUser user) {
        HashMap<String, String> result = new HashMap<>();

        AdhCouponInfo couponInfo = this.iAdhCouponInfoService.getById(couponId);
        Integer stockNum = couponInfo.getStockNum();
        Integer receiveNum = Integer.parseInt(couponInfo.getReceiveNum());
        if (!(receiveNum < stockNum)) {
            result.put("code", "601");
            result.put("message", "该优惠券已经领完");
            return result;
        }

        Integer useLimit = couponInfo.getUseLimit();
        LambdaQueryWrapper<AdhCouponOrder> query = new LambdaQueryWrapper<AdhCouponOrder>();
        query.eq(AdhCouponOrder::getCouponId, couponId);
        query.eq(AdhCouponOrder::getUserId, user.getId());
        List<AdhCouponOrder> list = this.iAdhCouponOrderService.list(query);
        if (!(list.size() < useLimit)) {
            result.put("code", "602");
            result.put("message", "您已经领取该优惠券，限每人最多领取" + useLimit + "张");
            return result;
        }

        AdhMerchInfo merchInfo = this.adhMerchInfoService.getById(merchId);
        AdhCouponOrder adhCouponOrder = new AdhCouponOrder();
        adhCouponOrder.setCouponNo(getOrderIdByUUId());
        adhCouponOrder.setMerchId(merchId);
        adhCouponOrder.setMerchName(merchInfo.getMerchName());
        adhCouponOrder.setUserPhone(user.getUserPhone());
        adhCouponOrder.setUserName(user.getNickName());
        adhCouponOrder.setUserId(user.getId());
        adhCouponOrder.setCouponName(couponInfo.getCouponName());
        adhCouponOrder.setCouponDiscount(couponInfo.getCouponDiscount());
        adhCouponOrder.setCouponType(couponInfo.getCouponType());
        adhCouponOrder.setValidBeginTime(couponInfo.getValidBeginTime());
        adhCouponOrder.setValidEndTime(couponInfo.getValidEndTime());
        adhCouponOrder.setAdvancePurchasePrice(couponInfo.getAdvancePurchasePrice());
        adhCouponOrder.setUseDesc(couponInfo.getUseDesc());
        adhCouponOrder.setReceiveDate(new Date());
        adhCouponOrder.setCouponId(couponId);
        this.iAdhCouponOrderService.save(adhCouponOrder);

        couponInfo.setReceiveNum(String.valueOf(receiveNum + 1));
        this.iAdhCouponInfoService.updateById(couponInfo);
        result.put("code", "200");
        return result;
    }
    /**
     * @param merchId
     * @param couponId
     * @param user
     * @return java.lang.String
     * @author leikai
     * @date 2022/03/11/0011 18:32
     */
    public Map<String, String> receiveBmCoupon(String merchId, String couponId, AdhUser user,String bmName,String bmEmail,String bmPhone,String bmRemark) {
        HashMap<String, String> result = new HashMap<>();

        AdhCouponInfo couponInfo = this.iAdhCouponInfoService.getById(couponId);
        Integer stockNum = couponInfo.getStockNum();
        Integer receiveNum = Integer.parseInt(couponInfo.getReceiveNum());
        if (!(receiveNum < stockNum)) {
            result.put("code", "601");
            result.put("message", "该优惠券已经领完");
            return result;
        }

        Integer useLimit = couponInfo.getUseLimit();
        LambdaQueryWrapper<AdhCouponOrder> query = new LambdaQueryWrapper<AdhCouponOrder>();
        query.eq(AdhCouponOrder::getCouponId, couponId);
        query.eq(AdhCouponOrder::getUserId, user.getId());
        List<AdhCouponOrder> list = this.iAdhCouponOrderService.list(query);
        if (!(list.size() < useLimit)) {
            result.put("code", "602");
            result.put("message", "您已经领取该优惠券，限每人最多领取" + useLimit + "张");
            return result;
        }

        AdhMerchInfo merchInfo = this.adhMerchInfoService.getById(merchId);
        AdhCouponOrder adhCouponOrder = new AdhCouponOrder();
        adhCouponOrder.setCouponNo(getOrderIdByUUId());
        adhCouponOrder.setMerchId(merchId);
        adhCouponOrder.setMerchName(merchInfo.getMerchName());
        adhCouponOrder.setUserPhone(user.getUserPhone());
        adhCouponOrder.setUserName(user.getNickName());
        adhCouponOrder.setUserId(user.getId());
        adhCouponOrder.setCouponName(couponInfo.getCouponName());
        adhCouponOrder.setCouponDiscount(couponInfo.getCouponDiscount());
        adhCouponOrder.setCouponType(couponInfo.getCouponType());
        adhCouponOrder.setValidBeginTime(couponInfo.getValidBeginTime());
        adhCouponOrder.setValidEndTime(couponInfo.getValidEndTime());
        adhCouponOrder.setAdvancePurchasePrice(couponInfo.getAdvancePurchasePrice());
        adhCouponOrder.setUseDesc(couponInfo.getUseDesc());
        adhCouponOrder.setReceiveDate(new Date());
        adhCouponOrder.setCouponId(couponId);
        adhCouponOrder.setBmEmail(bmEmail);
        adhCouponOrder.setBmName(bmName);
        adhCouponOrder.setBmPhone(bmPhone);
        adhCouponOrder.setBmRemark(bmRemark);
        this.iAdhCouponOrderService.save(adhCouponOrder);

        couponInfo.setReceiveNum(String.valueOf(receiveNum + 1));
        this.iAdhCouponInfoService.updateById(couponInfo);
        result.put("code", "200");
        return result;
    }


    private String getOrderIdByUUId() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("HHmmss");
        String first = dateFormat.format(new Date());
        int hashCodeV = UUID.randomUUID().toString().hashCode();
        if (hashCodeV < 0) {
            hashCodeV = -hashCodeV;
        }
        return first + String.format("%010d", hashCodeV);
    }
    //刘彪 增加我的优惠券只查询折扣券和代金券
    public List<?> queryCouponOrder(String userId, Integer useStatus) {
        HashMap<String, Object> paramMap = new HashMap<>();
        String sql = "SELECT b.*,a.use_status,a.coupon_no FROM adh_coupon_order a\n" +
                "LEFT JOIN(\n" +
                "\tSELECT * FROM adh_coupon_info\n" +
                ") b ON b.id = a.coupon_id WHERE  (b.coupon_type='1' OR b.coupon_type='2')  and  a.user_id=:userId ";
        if (useStatus != null) {
            sql += " And use_status=:useStatus";
            paramMap.put("useStatus", useStatus);
        }
        paramMap.put("userId", userId);
        return this.jdbcTemplate.queryForListHump(sql, paramMap);
    }

    public List<?> queryCouponCheck(String userPhone) {
        String sql = "select b.*,a.check_date from adh_coupon_order a left join(\n" +
                "\tselect * from adh_coupon_info\n" +
                ") b on a.coupon_id=b.id\n" +
                "WHERE check_user=:userPhone AND use_status=1";
        return this.jdbcTemplate.queryForListHump(sql, ImmutableMap.of("userPhone", userPhone));
    }


    public void updateCouponStatus() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String thisDate = sdf.format(new Date());
        this.jdbcTemplate.execute("UPDATE adh_coupon_order SET use_status=2 WHERE use_status=0 AND DATE(valid_end_time)<DATE(STR_TO_DATE('" + thisDate + "','%Y-%m-%d'))");
        this.jdbcTemplate.execute("UPDATE adh_coupon_info SET coupon_status='3' WHERE coupon_status='2' and DATE(valid_end_time)<DATE(STR_TO_DATE('" + thisDate + "','%Y-%m-%d'))");
    }
}
